const cloud = require('wx-server-sdk')
const xlsx = require('node-xlsx')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const excelCollection = db.collection('excel_data')

exports.main = async (event, context) => {
  try {
    const { fileID } = event
    
    // 下载云存储中的文件
    const res = await cloud.downloadFile({
      fileID: fileID
    })
    
    const buffer = res.fileContent
    const sheets = xlsx.parse(buffer)
    
    // 解析第一个sheet
    const sheet = sheets[0]
    const data = sheet.data
    
    // 存储到数据库
    await excelCollection.add({
      data: {
        fileID: fileID,
        sheetName: sheet.name,
        content: data,
        createTime: db.serverDate()
      }
    })
    
    return {
      success: true,
      data: data,
      msg: '解析成功'
    }
    
  } catch (err) {
    return {
      success: false,
      msg: '解析失败',
      error: err
    }
  }
} 